import { 
  Camera,  
  Mesh, 
  PlaneBufferGeometry, 
  Scene, 
  ShaderMaterial, 
  Vector3, 
  WebGLRenderer 
} from "three"

const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.style.width = '100vw'
canvas.style.height = '100vh'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new Camera()
camera.position.z = 1
const plane = new PlaneBufferGeometry(2, 3)

// 片元着色器
const fragmentShader = `
#include <common>

// 运行时间（以秒计）
uniform vec3 u_resolution;
uniform float u_time;

void main() {
  // 格式化坐标，让值落在 0.0 到 1.0 之间
  vec2 st = gl_FragCoord.xy/u_resolution.xy;

  float time =  - (u_time / 100.0);

  float color1 = step(0., st.x + time);
  float color2 = step(0.25, st.x + time);
  float color3 = step(0.5, st.x + time);
  float color4 = step(0.75, st.x + time);

  vec3 color = vec3(0.);

  color = mix(color, vec3(1., 0., 0.), color1);
  color = mix(color, vec3(0., 1., 0.), color2);
  color = mix(color, vec3(0., 0., 1.), color3);
  color = mix(color, vec3(1., 0., 1.), color4);

  // 将 x y 映射到红色与绿色通道
  gl_FragColor = vec4(color, 1.);
}
`

// const material = new MeshBasicMaterial({ color: 'red' })
const uniforms = {
  u_time: { value: 0.0 },
  u_resolution: { value: new Vector3() },
}
const material = new ShaderMaterial({
  fragmentShader,
  uniforms
})
scene.add(new Mesh(plane, material))

function render(time: number) {
  // 转化成秒
  time *= 0.001

  const canvas = renderer.domElement
  uniforms.u_resolution.value.set(canvas.width, canvas.height, 1)

  // uniforms.u_time.value = 0
  if (uniforms.u_time.value >= 100) {
    uniforms.u_time.value = 0
  } else {
    uniforms.u_time.value += 0.5
  }

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)